package com.cby.android.library.base

import android.app.Application
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.cby.android.library.mvi.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

abstract class BaseStateViewModel<S: IState, I:IIntent>(application: Application) : BaseViewModel(application),
    IModel<S, I> {

    override val intents: Channel<I> = Channel(Channel.UNLIMITED)

    private val _state = MutableLiveData<S>()

    override val state: LiveData<S>
        get() = _state

    init {
        handlerIntent()
    }

    private fun handlerIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect {
                dispatch(it)
            }
        }
    }

    abstract fun dispatch(intent : I)

    fun fetchDataWithStatus(block: suspend () -> Boolean){
        viewModelScope.launch(Dispatchers.IO) {
            try {
                showLoading()
                // 请求数据代码块
                val result: Boolean = block()

                if(result){
                    showContent()
                }else{
                    showEmpty()
                }
            } catch (e: Exception) {
                showError(e.message)
            }
        }
    }

    fun fetchDataWithNoStatus(block: suspend () -> Unit) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                block()
            } catch (e: Exception) {
                showError(e.message)
            }
        }
    }

    fun updateState(state: S) {
        _state.postValue(state)
    }


}